﻿using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using ApplicationGenerator.Versions.BusinessLogic;

namespace ApplicationGenerator.Versions.Forms
{
    /// <summary>
    /// Edytor dla wersji. Używany w celu wyświetlenia formatki wyświetlającej wersje danego
    /// typu elementu
    /// </summary>
    public class VersionEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (context != null)
            {
                if (context.Instance != null)
                {
                    VersionTypeAttribute[] versionAttributes = (VersionTypeAttribute[])context.Instance.GetType().GetProperty(context.PropertyDescriptor.Name).GetCustomAttributes(typeof(VersionTypeAttribute),true);
                    if (versionAttributes == null || versionAttributes.Length == 0)
                    {
                        throw new Exception("Property używające edytora wersji musi być opatrzone atrybute VersionTypeAttribute");
                    }

                    IWindowsFormsEditorService editorService = null;

                    if (provider != null)
                    {
                        editorService =
                            provider.GetService(
                            typeof(IWindowsFormsEditorService))
                            as IWindowsFormsEditorService;
                    }
                    if (editorService != null)
                    {
                        VersionForm versionForm = new VersionForm();
                        versionForm.VersionType = versionAttributes[0].VersionType;
                        versionForm.InitializeVersions();
                        if (editorService.ShowDialog(versionForm) == DialogResult.OK)
                        {
                            value = versionForm.SelectedVersionInfo;
                        }
                    }
                }
            }
            return value;
        }
    }
}
